package com.fc.v2.controller.api;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fc.v2.WX.WXParam;
import com.fc.v2.WX.WXUrl;
import com.fc.v2.common.domain.AjaxResult;
import com.fc.v2.model.auto.*;
import com.fc.v2.service.*;
import com.fc.v2.util.StringUtils;
import com.fc.v2.util.WechatDecryptDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@Api(value = "小程序用户API")
@Controller
@RequestMapping("/api/miniUser")
public class AMiniUserController {

    private static final Logger log = LoggerFactory.getLogger(AMiniUserController.class);

    @Autowired
    private SessionService sessionService;

    /**
     * 登录
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestParam(value = "session_key",required = false) String skey, String code) {
        if(StringUtils.isEmpty(skey) && StringUtils.isEmpty(code)){
            return AjaxResult.error("请传入参数");
        }

        //查询code
        if(StringUtils.isEmpty(skey) && StringUtils.isNotEmpty(code)){
            //获取openid skey
            String res = code2Session(code);

            ObjectMapper mapper=new ObjectMapper();
            Session session=null;
            try {
                session = mapper.readValue(res, Session.class);
                //该方法操作数据库并设置了session里的userid和gain_time，所以后面可以直接返回session
                sessionService.insertOrUpdate(session);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return AjaxResult.error("微信服务器响应错误");
            }
            return AjaxResult.successData(200,session);
        }else{
            //sessionKey不为空，返回查询结果
            SessionExample e = new SessionExample();
            e.createCriteria().andSkeyEqualTo(skey);
            List<Session> sessions = sessionService.selectByExample(e);
            if(sessions.size()==0){
                return AjaxResult.error(501,"sessionKey无效，请重新获取");
            }else{
                Session session = sessions.get(0);
                return AjaxResult.success();
            }
        }

    }

    /**
     * 获取openid skey
     * @param code
     * @return
     */
    private String code2Session(String code){
        if(StringUtils.isNotEmpty(code)){
            String appID = WXParam.APPID;
            String appSecret = WXParam.APP_SECRET;
            String url = WXUrl.code2SessionUrl;
            HashMap<String, Object> map = new HashMap<>();
            map.put("appid",appID);
            map.put("secret",appSecret);
            map.put("js_code",code);
            map.put("grant_type","authorization_code");
            String res = HttpUtil.get(url, map);
            return res;
        }
        return null;
    }


    /**
     * 获取手机号
     * @param
     * @return
     */
    @ApiOperation(value = "获取手机号", notes = "获取手机号")
    @PostMapping("/get/phone")
    @ResponseBody
    public Object getPhone(@RequestBody String body){
        JSONObject jsonObject = JSONUtil.parseObj(body);

        String  encryptedData;
        String  iv;
        String sessionKey;
        try {
            encryptedData = jsonObject.get("encryptedData").toString();
            iv = jsonObject.get("iv").toString();
            sessionKey = jsonObject.get("sessionKey").toString();
            log.debug("encryptedData:{}",encryptedData);

            log.debug("iv:{}",iv);

            log.debug("skey:{}",sessionKey);
        }catch (NullPointerException e){
            return AjaxResult.error("传入数据字段有误");
        }

        try {
            String data = WechatDecryptDataUtil.decryptData(encryptedData, sessionKey, iv);
            JSONObject dataObject = JSONUtil.parseObj(data);
            return AjaxResult.successData(200,dataObject);
        }catch (Exception e){
            return AjaxResult.error("解密失败，可能为sessionKey无效");
        }

    }



}
